import webview
import easygui
import os
import shutil
import json
import random
import win32com.client
from win32 import win32gui, win32print
from win32.lib import win32con
from win32.win32api import GetSystemMetrics
import time
import requests
import pyzipper
import pyautogui
import wppAction
import webbrowser
from http.cookiejar import MozillaCookieJar
import vicent_pwd
acc_access = None
pushing = False

def read_jsonFile(file):
    with open(file,"r")as f:
        return json.load(f)
def write_jsonFile(file,data):
    with open(file,"w")as f:
        json.dump(data,f)
if not os.path.exists("now_wpp.json"):
    now_wpp = {"id": "", "char": "", "everyDay_open":False, "everyDay_path":"", "open": False}
    write_jsonFile("now_wpp.json",now_wpp)
if os.path.exists("cookies.json"):
    with open('cookies.json', 'r',encoding="utf-8") as f:
        cookies = json.load(f)
        f.close()
else:
    cookies = None

if os.path.exists("inf.json"):
    inf_data = read_jsonFile("inf.json")
else:
    inf_data={
        "v":"1.0.0",
    }
    write_jsonFile("inf.json",inf_data)
# 自启动配置加载
if os.path.exists("autoStartConfig.json"):
    autoStartConfig = read_jsonFile("autoStartConfig.json")
else:
    autoStartConfig={
        "wpp":False,
        "char":False,
        "easyDesktop":False,
    }
    write_jsonFile("autoStartConfig.json",autoStartConfig)
def create_id():
    if not os.path.exists("wallpaper"):
        os.makedirs("wallpaper")
    a_list="A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9".split(" ")
    while True:
        wpp_id=""
        for i in range(10):
            wpp_id+=random.sample(a_list,1)[0]
        if os.path.exists("wallpaper/"+wpp_id):
            continue
        break
    return wpp_id
def check_fix(json_path):
    with open(json_path,"r")as f:
        charData = json.load(f)
        f.close()
    dataInf={
        "char_name":{"defeat":"[修复的]未知角色","type_str":"<class 'str'>"},
        "char_id":{"defeat":create_id(),"type_str":"<class 'str'>"},
        "banner":{"defeat":"./mhkj_logo.png","type_str":"<class 'str'>"},
        "introduce":{"defeat":"没有简介","type_str":"<class 'str'>"},
        "border_color":{"defeat":"#FFFFFF","type_str":"<class 'str'>"},
        "font_color":{"defeat":"#FFFFFF","type_str":"<class 'str'>"},
        "bg_color":{"defeat":"#FFFFFF","type_str":"<class 'str'>"},
        "chat":{"defeat":{},"type_str":"<class 'dict'>"},
        "rule":{"defeat":[],"type_str":"<class 'list'>"}
    }
    fix_list = []
    for charDataKey in dataInf:
        if charDataKey in charData:
            if str(type(charData[charDataKey])) != dataInf[charDataKey]["type_str"]:
                fix_list.append(charDataKey)
        else:
            fix_list.append(charDataKey)
    if len(fix_list)!=0:
        print("正在修复"+json_path+"的错误...")
        if not os.path.exists(json_path+".error.json"):
            shutil.copy(json_path,json_path+".error.json")
        for fix_key in fix_list:
            charData[fix_key]=dataInf[fix_key]["defeat"]
        with open(json_path,"w")as f:
            json.dump(charData,f)
# 处理chars.json
def chars_data_load():
    if os.path.exists("char/chars.json"):
        with open("char/chars.json","r")as f:
            chars=json.load(f)
            f.close()
        del_list = []
        for char in chars:
            if not os.path.exists("char/"+chars[char]["key_name"]):
                del_list.append(char)
        for del_c in del_list:
            del chars[del_c]
        # is_chars_exists = True
    else:
        chars={}
        is_chars_exists = False

    inf_part={
        "char_name":"name",
        "char_id":"key_name",
        "introduce":"introduce",
        "banner":"banner"
    }
    for file_name in os.listdir("char"):
        full_path = os.path.join("char", file_name)
        if not os.path.isfile(full_path):
            check_fix(os.path.join(full_path,"char_inf.json"))
            with open(os.path.join(full_path,"char_inf.json"),"r")as f:
                this_char = json.load(f)
                f.close()
            if this_char["char_id"] in chars:
                for i_p in inf_part:
                    chars[this_char["char_id"]][inf_part[i_p]]=this_char[i_p]
            else:
                chars[this_char["char_id"]]={
                    "name":this_char["char_name"],
                    "key_name":this_char["char_id"],
                    "banner":this_char["banner"],
                    "introduce":this_char["introduce"],
                    "create_local":True,
                    "v":None,
                    "net_id":None
                }
    with open("char/chars.json","w")as f:
        json.dump(chars,f)
        f.close()
chars_data_load()

def login_cv(acc,password):
    global cookies,acc_access
    login_r = requests.post("http://127.0.0.1:8001/account/login/",data=json.dumps({"key":acc,"pw":password}))
    if login_r.status_code==200:
        data = json.loads(str(login_r.content,"utf-8"))
        if data["success"]==True:
            cookies=login_r.cookies.get_dict()
            acc_access = data["access"]
            print(cookies)
            with open('cookies.json', 'w') as f:
                json.dump(cookies,f)
                f.close()
            return data
        else:
            window.evaluate_js('document.getElementById("login_msg").style.color="red";document.getElementById("login_msg").innerHTML='+data["msg"]+";")
            return data
    else:
        window.evaluate_js('document.getElementById("login_msg").style.color="red";document.getElementById("login_msg").innerHTML="网络错误";')
        return {"success":False,"msg":"network error"}


def judgeprocess(processname):
    WMI = win32com.client.GetObject('winmgmts:')
    processCodeCov = WMI.ExecQuery('select * from Win32_Process where Name="%s"' % processname)
    if len(processCodeCov) > 0:
        return True
    else:
        return False
def settting_effect():
    try:
        if setting_data["dict"]["autoStart"]["value"]==True:
            start_up = os.path.join(os.path.expanduser("~"), r'AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup')
            vbs = '''
            Dim Wsh
            set ws = createobject("wscript.shell")
            ws.currentdirectory = "'''+os.getcwd()+'''"
            CurrentPath = createobject("Scripting.FileSystemObject").GetFolder(".").Path 
            ws.Run "starter.exe"
            Set Wsh=NoThing
            WScript.quit'''
            with open(start_up+r"\\wallpapaer_v.vbs","w")as f:
                f.write(vbs)
                f.close()
        else:
            if os.path.exists(os.path.join(os.path.expanduser("~"), r'AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\wallpapaer_v.vbs')):
                os.remove(os.path.join(os.path.expanduser("~"), r'AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\wallpapaer_v.vbs'))
    except Exception as e:
        easygui.msgbox("生效设置时发生错误：\n"+e)
if not os.path.exists("setting.json"):
    with open("setting.json","w")as f:
        setting_data={
            "list":[False,False],
            "dict":{
                "autoStart":{"index":0,"name":"开机自启动","value":False},
                "randomWpp":{"index":2,"name":"启动时随机壁纸","value":False}
            }
        }
        json.dump(setting_data,f)
        f.close()
else:
    with open("setting.json","r")as f:
        setting_data=json.load(f)
        f.close()
settting_effect()
# if os.path.exists("char/chars.json"):
#     with open("char/chars.json","r")as f:
#         chars_data = json.load(f)
# else:
#     with open("char/chars.json","w")as f:
#         json.dump({},f)
#         chars_data = {}

def pack_html(vid_path,need_sound,need_jx,size,offset,save_path):
    global bl
    offset = (int(offset)/bl)
    with open("wpp_vid_play.txt","r",encoding="utf-8")as f:
        wppHtml = f.read()
        f.close()
    wppHtml = wppHtml.replace("!<-vid->!",vid_path)
    if need_sound == True:
        wppHtml = wppHtml.replace("!<-sound->!","")
    else:
        wppHtml=wppHtml.replace("!<-sound->!","muted")
    if need_jx == True:
        wppHtml=wppHtml.replace("!<-jx->!","video_jx")
    else:
        wppHtml=wppHtml.replace("!<-jx->!","")
    wppHtml = wppHtml.replace("!<-size->!",str(size))
    wppHtml = wppHtml.replace("!<-offset->!",str(offset))
    with open(save_path,"w")as f:
        f.write(wppHtml)
bl = 1
def compress_folder_zipfile(folder_path, output_path):
    with pyzipper.AESZipFile(
        output_path, 
        'w', 
        compression=pyzipper.ZIP_LZMA,  # 高压缩率
        encryption=pyzipper.WZ_AES      # 使用AES加密
    ) as zf:
        zf.setpassword(vicent_pwd.get_pwd("wpp").encode('utf-8'))
        
        # 遍历文件夹所有内容
        for root, _, files in os.walk(folder_path):
            for file in files:
                file_path = os.path.join(root, file)
                # 计算相对路径（保持目录结构）
                arcname = os.path.relpath(file_path, folder_path)
                zf.write(file_path, arcname)
def upload_file(file_path,url):
    global cookies
    pushing = True
    print("上传文件："+file_path)
    print("上传接口："+url)
    upload_file = {'file': open(file_path, 'rb')}
    upload_r = requests.post(url,files=upload_file,cookies=cookies)
    orignal_content = str(upload_r.content,"utf-8")
    sc=upload_r.status_code
    if sc == 200:
        upload_r=json.loads(str(upload_r.content,"utf-8"))
        return upload_r
    else:
        webview.create_window(html=orignal_content,title="上传失败",width=500,height=500)
        return {"success":False,"msg":"network error "+str(sc)}
def read_charData(cid):
    return read_jsonFile("char/"+cid+"/char_inf.json")
def get_userAccInf():
    global cookies,acc_access
    print(cookies)
    print(acc_access)
    u_data = requests.get("http://127.0.0.1:8001/user_data/privacy/",cookies=cookies)
    if u_data.status_code == 200:
        u_data = json.loads(str(u_data.content,"utf-8"))
        return u_data
    return u_data
class API:
    def get_webChar(self):
        out_data = {}
        chars_data = read_jsonFile("char/chars.json")
        for c in chars_data:
            if chars_data[c]["create_local"]==False:
                out_data[chars_data[c]["net_id"]]=chars_data[c]["v"]
        return {"success":True,"data":out_data}
    def get_loginAccess(self):
        global cookies
        return cookies
    def go_link(self,url):
        webbrowser.open(url)
    def is_ok(self):
        return True
    def check_runState(self):
        runState = {
            "wpp":judgeprocess("wppRunner.exe"),
            "char":judgeprocess("charRunner.exe"),
            "easyDesktop":judgeprocess("easyDesktop.exe"),
        }
        return {"success":True,"data":runState}
    def get_autoStartConfig(self):
        global autoStartConfig
        return {"success":True,"data":autoStartConfig}
    def set_autoStartConfig(self,app,state):
        global autoStartConfig
        autoStartConfig[app]=state
        write_jsonFile("autoStartConfig.json",autoStartConfig)
        return {"success":True}
    def choise_file(self):
        print("file")
        file_types = ('Video Files (*.mp4;*.mov;*.flv;*.webm)', 'All files (*.*)')
        # file_types = ('Image Files (*.bmp;*.jpg;*.gif)', 'All files (*.*)')
        data = window.create_file_dialog(webview.OPEN_DIALOG, allow_multiple=True, file_types=file_types)
        if data == None:
            return {"success":False,"msg":"用户取消"}
        else:
            return {"success":True,"data":data}
    def wwp_register(self,wpp_id,wpp_type,banner,name="未命名",editor="未知",artist="未知",describe="暂无简介",size="unkonw"):
        print("注册壁纸：开始进行")
        if os.path.exists("wapapers.json"):
            with open("wapapers.json","r")as f:
                wpp_data = json.load(f)
                f.close()
        else:
            wpp_data = {}
        print("开始抽取id")
        this_wpp = {"id":wpp_id,"type":wpp_type,"name":name,"img":banner,"editor":editor,"artist":artist,"describe":describe,"size":size}
        wpp_data[wpp_id]=this_wpp
        with open("wapapers.json","w")as f:
            json.dump(wpp_data,f)
        print("壁纸注册完成")
    def get_wpp_list(self):
        if os.path.exists("wapapers.json"):
            with open("wapapers.json","r",encoding="utf-8")as f:
                wpp_data = json.load(f)
            print(wpp_data)
            return {"success":True,"data":wpp_data}
        else:
            return {"success":False,"msg":"数据文件不存在或损坏"}
    def add_Only_html_wp(self,dir_path,name,editer,html_file,banner=None):
        wpp_id=create_id()
        res_check_list = ["index.html","banner.png","banner.jpg","banner.gif"]
        ok_count=0
        for res_n in res_check_list:
            if os.path.exists(os.path.join(dir_path,res_n))==True:
                ok_count+=1
        if ok_count < 2:
            return {"success":False,"msg":"资源验证不通过"}
        shutil.copytree(dir_path,"wallpaper/"+wpp_id)
        print("资源复制完成")
        paper_data={
            "type":"only_html",
            "html_file":html_file,
            "banner":banner,
            "name":name,
            "editer":editer,
            "char_link":"unuse",
            "wpp_id":wpp_id
        }
        with open("wallpaper/"+wpp_id+"/inf.json","w")as f:
            json.dump(paper_data,f)
        print("html壁纸迁移完毕")
        return {"success":True,"wpp_id":wpp_id}
    def choise_dir(self):
        data=easygui.diropenbox()
        if data == None:
            return {"success":False,"msg":"用户取消"}
        else:
            return {"success":True,"data":data}
    def add_Only_vid_wp(self,vid_path,name,editer,need_fz,need_sound):
        wpp_id=create_id()
        if os.path.exists("wapaper/"+name):
            return {"success":False,"msg":"已有同名壁纸，请更换名称"}
        else:
            os.makedirs("wallpaper/"+wpp_id)
            shutil.copyfile(vid_path,"wallpaper/"+wpp_id+"/video.mp4")
            vid_file_name="video.mp4"
            paper_data={
                "type":"only_vid",
                "vid_file":vid_file_name,
                "banner":"img.jpg",
                "name":name,
                "editer":editer,
                "char_link":"unuse",
                "wpp_id":wpp_id
            }
            with open("wallpaper/"+wpp_id+"/inf.json","w")as f:
                json.dump(paper_data,f)
        print("文件迁移完成...")
        pack_data = {"vid":"wallpaper/"+wpp_id+"/video.mp4","sound":need_sound,"size":100,"offset":0,"is_jx":need_fz}
        with open("wallpaper/"+wpp_id+"/pack.json","w")as f:
            json.dump(pack_data,f)
            f.close()
        pack_html("wallpaper/"+wpp_id+"/video.mp4",need_sound,need_fz,100,0,"wallpaper/"+wpp_id+"/wpp.html")
        return {"success":True,"wpp_id":wpp_id,"msg":"壁纸 "+name+" 已添加完成"}
    def start_service(self):
        try:
            if judgeprocess("wppRunner.exe") == False:
                os.startfile("wppRunner.exe")
            while True:
                if judgeprocess("wppRunner.exe") == True:
                    break
                time.sleep(1)
            return {"success":True}
        except:
            return {"success":False}
    def start_wpp(self,wpp_id):
        try:
            set_wpp_data = read_jsonFile("now_wpp.json")
            set_wpp_data["id"]=wpp_id
            set_wpp_data["open"]=True
            write_jsonFile("now_wpp.json",set_wpp_data)
            # os.startfile("start_wpp.vbs")
            if judgeprocess("wppRunner.exe") == False:
                os.startfile("wppRunner.exe")
            wait_wppLoad()
            return {"success":True}
        except Exception as e:
            easygui.msgbox("打开时发生错误！以下是错误信息\n"+str(e),"壁纸启动错误")
        return {"success":False}
    def is_wppService_run(self):
        try:
            if judgeprocess("wppRunner.exe")==True:
                return {"success":True,"result":True}
            else:
                return {"success":True,"result":False}
        except Exception as e:
            return {"success":False,"msg":"接口错误："+e}
    def is_wpp_run(self):
        try:
            if judgeprocess("wppRunner.exe")==True:
                with open("now_wpp.json","r")as f:
                    wppData = json.load(f)
                    f.close()
                return {"success":True,"result":True,"wppId":wppData["id"],"full":wppData}
            else:
                return {"success":True,"result":False}
        except Exception as e:
            return {"success":False,"msg":"接口错误："+e}
    def is_char_run(self):
        try:
            if judgeprocess("char_runner.exe")==True:
                with open("now_wpp.json","r")as f:
                    wppData = json.load(f)
                    f.close()
                return {"success":True,"result":True,"charId":wppData["char"]}
            else:
                return {"success":True,"result":False}
        except Exception as e:
            return {"success":False,"msg":"接口错误："+e}
    def stop_wpp(self):
        wpp_stateData = read_jsonFile("now_wpp.json")
        wpp_stateData["open"]=False
        write_jsonFile("now_wpp.json",wpp_stateData)
        return {"success":True}
    def start_ED(self):
        if judgeprocess("easyDesktop.exe")==False:
            if os.path.exists("easyDesktop.exe")==False:
                easygui.msgbox("easyDesktop.exe丢失")
            else:
                os.startfile("easyDesktop.exe")
    def stop_ED(self):
        os.popen("taskkill /F /im easyDesktop.exe")
    def get_setting(self):
        global setting_data
        name_list = []
        for obj in setting_data["dict"]:
            print(obj)
            name_list.append(setting_data["dict"][obj]["name"])
        return {"success":True,"name_list":name_list,"value":setting_data["list"]}
    def save_setting(self,value):
        global setting_data
        range_i = 0
        for key in setting_data["dict"].keys():
            setting_data["dict"][key]["value"]=value[range_i]
            range_i+=1
        setting_data["list"]=value
        with open("setting.json","w")as f:
            json.dump(setting_data,f)
            f.close()
        settting_effect()
        return {"success":True}
    def err_report(self,err):
        easygui.msgbox(err)
    def remove_wpp(self,wpp_id):
        shutil.rmtree("wallpaper/"+wpp_id)
        with open("wapapers.json","r",encoding="utf-8")as f:
            wpp_data = json.load(f)
        del wpp_data[wpp_id]
        with open("wapapers.json","w",encoding="utf-8")as f:
            json.dump(wpp_data,f)
        return {"success":True}
    def get_charRES_web(self):
        res_r = requests.get("https://api.code-vicent.top/wpp/content/char/list")
        res_data = json.loads(str(res_r.content,"utf-8"))
        return {"success":True,"data":res_data["data"],"len":len(res_data)}
    def download_char(self,char_key):
        wppAction.download_char(char_key)
        return {"success":True}
    def get_charRES_local(self):
        if os.path.exists("char/chars.json"):
            with open("char/chars.json","r")as f:
                load_res_data= json.load(f)
                f.close()
            res_data = []
            try:
                for key in load_res_data.keys():
                    res_data.append(load_res_data[key])
            except:
                pass
        else:
            res_data = []
        return {"success":True,"data":res_data,"len":len(res_data)}
    def get_charRES_local_original(self):
        if os.path.exists("char/chars.json"):
            with open("char/chars.json","r")as f:
                res_data= json.load(f)
                f.close()
        else:
            res_data = {}
        return {"success":True,"data":res_data,"len":len(res_data)}
    def del_char(self,char_key):
        print(char_key)
        try:
            shutil.rmtree("char/"+char_key)
        except:
            pass
        with open("char/chars.json","r")as f:
            d = json.load(f)
            f.close()
        del d[char_key]
        with open("char/chars.json","w")as f:
            json.dump(d,f)
            f.close()
        return {"success":True}
    def start_char(self,char):
        with open("now_wpp.json","r")as f:
            d = json.load(f)
            f.close()
        d["char"] = char
        with open("now_wpp.json","w")as f:
            json.dump(d,f)
            f.close
        os.popen("taskkill /F /im char_runner.exe").read()
        os.startfile("char_runner.exe")
        return {"success":True}
    def get_screen(self):
        screen_width, screen_height = pyautogui.size()
        return {"w":screen_width,"h":screen_height}
    def get_wppPackData(self,wppId):
        if os.path.exists("wapapers.json"):
            with open("wapapers.json","r")as f:
                wpp_data = json.load(f)
                f.close()
        try:
            with open("wallpaper/"+wppId+"/pack.json","r")as f:
                data = json.load(f)
                f.close()
            # with open("wallpaper/"+wppId+"/inf.json","r")as f:
            #     inf_Jdata = json.load(f)
            #     f.close()
        except:
            data = None
        # return {"pack":data,"inf":inf_Jdata,"global":wpp_data[wppId]}
        return {"pack":data,"inf":wpp_data[wppId]}
    def update_wppPack(self,wppId,name,editer,jx,sound,size,offset,char_link,wpp_type):
        inf_data = read_jsonFile("wallpaper/"+wppId+"/inf.json")
        if wpp_type == "video":
            pack_data = read_jsonFile("wallpaper/"+wppId+"/pack.json")
        inf_data["name"] = name
        inf_data["editer"] = editer
        if wpp_type == "video":
            pack_data["is_jx"] = jx
            pack_data["sound"] = sound
            pack_data["size"] = size
            pack_data["offset"] = offset
        inf_data["char_link"] = char_link
        if wpp_type == "video":
            pack_html("wallpaper/"+wppId+"/video.mp4",sound,jx,size,offset,"wallpaper/"+wppId+"/wpp.html")
        write_jsonFile("wallpaper/"+wppId+"/inf.json",inf_data)
        if wpp_type == "video":
            write_jsonFile("wallpaper/"+wppId+"/pack.json",pack_data)
        wpps_data = read_jsonFile("wapapers.json")
        wpps_data[wppId]["name"]=name
        wpps_data[wppId]["artist"]=editer
        wpps_data[wppId]["char_link"]=char_link
        write_jsonFile("wapapers.json",wpps_data)
        return {"success":True}
    def stop_char(self):
        os.popen("taskkill /F /im char_runner.exe")
        while True:
            if judgeprocess("char_runner.exe")==False:
                break
            time.sleep(0.5)
        return {"success":True}
    def set_everyDay_state(self,value):
        now_wpp = read_jsonFile("now_wpp.json")
        now_wpp["everyDay_open"]=value
        print(value)
        write_jsonFile("now_wpp.json",now_wpp)
        return {"success":True}
    def set_everyDay_path(self,path):
        now_wpp = read_jsonFile("now_wpp.json")
        shutil.copyfile(path,"wallpaper/ed.mp4")
        now_wpp["everyDay_path"]=path
        print(path)
        write_jsonFile("now_wpp.json",now_wpp)
        return {"success":True}
    def get_ed_state(self):
        ed_d = read_jsonFile("now_wpp.json")
        try:
            return {"success":True,"data":{"on":ed_d["everyDay_open"]},"path":ed_d["everyDay_path"]}
        except:
            return {"success":True,"data":{"on":"off"},"path":"开启后每次启动壁纸前会先播放一次所选视频"}
    def report_bl(self,r_bl):
        global bl
        bl = r_bl
    def create_NewChar(self):
        new_id = create_id()
        os.makedirs("char/"+new_id)
        os.makedirs("char/"+new_id+"/voice")
        with open("char/"+new_id+"/char_inf.json","w")as f:
            json.dump({"char_name":"新角色","char_id":new_id},f)
            f.close()
        check_fix("char/"+new_id+"/char_inf.json")
        self.start_charEdit(new_id)
        chars_data_load()
        window.evaluate_js("load_charRES_local()")
    def cv_login(self,acc,pw):
        login_r = login_cv(acc,pw)
        window.evaluate_js("get_loginAccess()")
        return login_r
    def get_userInf(self):
        return get_userAccInf()
    def open_person(self):
        webbrowser.open("https://code-vicent.top/person")
    def plug_readData(self,plug_id):
        return read_jsonFile("plug/"+plug_id+".json")
    def plug_dumpData(slef,plug_id,data):
        write_jsonFile("plug/"+plug_id+".json",data)
    def get_v(self):
        inf_d = read_jsonFile("inf.json")
        return inf_d
    def check_update(self):
        inf_data = read_jsonFile("inf.json")
        u_r = requests.get("https://api.code-vicent.top/app/state/get_inf/wpp")
        if u_r.status_code == 200:
            u_data = json.loads(str(u_r.content,"utf-8"))
            if str(inf_data["v"]) != str(u_data["data"]["v"]):
                return {"success":True,"need_update":True,"data":u_data["data"],"inf":u_data["inf"]}
            else:
                return {"success":True,"need_update":False,"data":u_data["data"],"inf":u_data["inf"]}
        else:
            return {"success":False,"msg":"网络错误："+str(u_r.status_code)}
    def start_charEdit(self,char_id):
        chars = read_jsonFile("char/chars.json")
        try:
            if chars[char_id]["create_local"]==False:
                return
        except:
            pass
        class charEditAPIClass:
            def get_char_data(self):
                with open("char/"+char_id+"/char_inf.json","r",encoding="utf-8")as f:
                    data = json.load(f)
                return data
            def file_select(self,f_type):
                base_path ={
                    "image":"char/"+char_id+"/",
                    "audio":"char/"+char_id+"/voice/"
                }
                data = edit_window.create_file_dialog(webview.OPEN_DIALOG)
                if data == None:
                    return {"success":False,"msg":"用户取消"}
                else:
                    data = data[0]
                    local_path=base_path[f_type]+os.path.basename(data)
                    if not os.path.join(os.getcwd(),r"char\\"+char_id) in data:
                        if os.path.exists(local_path):
                            if not os.getcwd() in data:
                                os.remove(local_path)
                        try:
                            shutil.copy(data,local_path)
                        except:
                            pass
                    return {"success":True,"data":local_path}
            def save(self,charD):
                if not os.path.exists("char/"+charD["char_id"]):
                    os.rename("char/"+char_id,"char/"+charD["char_id"])
                    save_path = "char/"+charD["char_id"]
                else:
                    save_path = "char/"+char_id
                with open(save_path+"/char_inf.json","w",encoding="utf-8")as f:
                    json.dump(charD,f)
                chars_data_load()
                window.evaluate_js("load_charRES_local()")
                return {"success":True}
            def writeCSS(self,charID,css):
                with open("char/"+charID+"/plug.css","w",encoding="utf-8")as f:
                    f.write(css)
            def upload_char(self):
                global cookies,pushing
                if pushing==True: return
                pushing=True
                u_inf=get_userAccInf()
                if u_inf["success"]==False:
                    pushing = False
                    return {"success":False,"msg":"请先登录CodeVicent账号"}
                char_data = read_jsonFile("char/"+char_id+"/char_inf.json")
                if os.path.exists("char/"+char_id+".zip"):
                    os.remove("char/"+char_id+".zip")
                if os.path.exists("char/charPushData_"+char_id+".json"):
                    charPushData = read_jsonFile("char/charPushData_"+char_id+".json")
                else:
                    charPushData = {"v":0}
                print("开始压缩文件")
                compress_folder_zipfile("char/"+char_id,"char/"+char_id+".zip")
                print("压缩文件完成")
                print("开始上传char.zip")
                up_r = upload_file("./char/"+char_id+".zip","http://127.0.0.1:8001/files/upload/wpp_char/")
                print("上传完成")
                print(up_r)
                if up_r["success"]==True:
                    charPushData["zip"] = up_r["mid"]
                    zip_mid = up_r["mid"]
                    chars_indexInf = read_jsonFile("char/chars.json")
                    char_indexInf = chars_indexInf[char_id]
                    print("开始上传封面")
                    up_r=upload_file("char/"+char_id+"/"+char_data["banner"][1:len(char_data["banner"])-1],"http://127.0.0.1:8001/files/upload/wpp_charImg/")
                    print("上传完成")
                    print(up_r)
                    if up_r["success"]==True:
                        banner_mid=up_r["mid"]
                    else:
                        print(up_r)
                        pushing=False
                        return {"success":False,"msg":"上传封面失败"}
                    
                    # upload_data = {"charName":char_data["char_name"],"mid":zip_mid,"net_banner":banner_mid,"char_indexInf":char_indexInf}
                    upload_data = {
                        "title":char_data["char_name"],
                        "content_inf":{"pack":zip_mid,"introduce":char_data["introduce"]},
                        "banner":"http://127.0.0.1:8001/files/get/"+banner_mid,
                    }
                    charPushData["banner"]=banner_mid
                    if "cid" in charPushData:
                        upload_data["cid"]=charPushData["cid"]
                        upload_data["content_inf"]["v"]=charPushData["v"]
                    print("开始提交char发布")
                    push_r = requests.post("http://127.0.0.1:8001/content/upload/wpp_char",cookies=cookies,data=json.dumps(upload_data))
                    if push_r.status_code == 200:
                        push_r = json.loads(str(push_r.content,"utf-8"))
                        print(push_r)
                        print("提交完成")
                        if push_r["success"]==True:
                            charPushData["cid"]=push_r["id"]
                            charPushData["v"]+=1
                            write_jsonFile("char/charPushData_"+char_id+".json",charPushData)
                            write_jsonFile("char/chars.json",chars_indexInf)
                            pushing = False
                            return {"success":True}
                        else:
                            pushing = False
                            return {"success":False,"msg":push_r["msg"]}
                    else:
                        webview.create_window("错误", html=str(push_r.content,"utf-8"), width=500, height=300)
                        pushing = False
                        return {"success":False,"msg":"网络错误"}
                else:
                    print(up_r)
                    pushing = False
                    return {"success":False,"msg":"网络错误："+str(up_r["msg"])}
        # upload_file = {'file': open("char/"+char_id+".zip", 'rb')}
        charEditAPI=charEditAPIClass()
        edit_window = webview.create_window(
            "角色互动编辑",
            "char_edit.html",
            width=int(sw*1),
            height=int(sh*0.6),
            text_select=False,
            confirm_close=False,
            draggable=False,
            js_api=charEditAPI,
            easy_drag=False
        )
        
def wait_wppLoad():
    while True:
        if os.path.exists("start_run.key"):
            with open("start_run.key","r")as f:
                time_data=json.load(f)
                f.close()
            if int(time.time()) - int(time_data["time"])<5:
                break
        time.sleep(1)

def get_scaling_percentage():
    # 获取设备上下文
    hdc = win32gui.GetDC(None)
    
    # 获取系统 DPI
    LOGPIXELSX = 88  # Win32常量，用于获取每逻辑英寸的像素数
    dpi = win32print.GetDeviceCaps(hdc, LOGPIXELSX)

    # 释放设备上下文
    win32gui.ReleaseDC(None, hdc)

    # 计算缩放比例（标准 DPI 是 96）
    scaling_percentage = (dpi / 96)
    return scaling_percentage
def get_screen_size():
    hDC = win32gui.GetDC(0)
    # 横向分辨率
    w = win32print.GetDeviceCaps(hDC, win32con.DESKTOPHORZRES)
    # 纵向分辨率
    h = win32print.GetDeviceCaps(hDC, win32con.DESKTOPVERTRES)
    return w, h
def start_func():
    pass
    # charStore_r = requests.get("http://127.0.0.1:8000/app/wpp/res_store/char")
    # if charStore_r.status_code==200:
    #     with open("res_store_char.html","w")as f:
    #         f.write(str(charStore_r.content,"utf-8"))
sw,sh=get_screen_size()

api = API()
win_w=int(sw*0.8)
win_h=int(sh*0.7)
window = webview.create_window(
    '梦幻空间',
    "main_ui.html",
    width=win_w,
    height=win_h,
    text_select=False,
    confirm_close=False,
    draggable=False,
    js_api=api,
    easy_drag=False
)
webview.start(debug=True,func=start_func)